package com.xcms.member;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		String name=request.getParameter("name");
		String pwd= request.getParameter("pwd");
		String vali1=request.getParameter("vali");
		String errMsg="";
		String vali=request.getSession().getAttribute("vali").toString();
		if(vali==""||vali==null)
			errMsg+="验证码为空";
		//首先验证验证码正确不，不正确就提示
		if(vali.equals(vali1)) {
			//服务端的验证
			String ageStr = request.getParameter("age");
			int age = 0;
			if (ageStr != null) {
				age = Integer.parseInt(ageStr);
			} else {
				errMsg += "年龄不能为空!";
			}
			//说明服务端验证里面有错误，打印错误
			if (errMsg != "" || errMsg.length() > 0) {
				out.println(errMsg);
			} else {
				User user = new User();
				user.setName(name);
				user.setPassword(pwd);
				UserDAO.insert(user);
				out.print("<script language='javascript'>alert('恭喜你,注册成功');window.location.href='index2.jsp';</script>");
				//todo:放到数据库Mysql
				BufferedWriter bw = null;
				try {
					bw = new BufferedWriter(new FileWriter("C:\\Users\\hp\\IdeaProjects\\xcms\\info.txt", true));
					bw.write("名字：" + name + "\t密码：" + pwd + "\t年龄:" + age);
					bw.newLine();
					bw.close();
				} catch (IOException e) {
					throw new RuntimeException("存储数据失败" + e.getMessage());
				} finally {
					if (bw != null) {
						try {
							bw.close();
						} catch (IOException e) {
							throw new RuntimeException("关闭文件失败" + e.getMessage());
						}
					}
				}
			}
		}
		else{
			out.print("<script language='javascript'>alert('验证码错误！！！');window.location.href='register.jsp';</script>");
//

		}
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
